﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace Admx_Generator
{
    public partial class AdmxViewer : UserControl
    {
        private System.Resources.ResourceManager resMan = new System.Resources.ResourceManager("Admx_Generator.Localization.LocalizedStrings", typeof(AdmxViewer).Assembly);

        public AdmxViewer(AdmxFile admx)
        {
            InitializeComponent();
            List<char> allowedCharacters = Utilities.GetAllowedCharacters();
            this.fltTxtBxNamespace.AllowedCharacters.AddRange(allowedCharacters);
            this.fltTxtBxNamespace.AllowedCharacters.Add('.');

            this.fltTxtBxPrefix.AllowedCharacters.AddRange(allowedCharacters);
            this.fltTxtBxPrefix.AllowedCharacters.Add('_');

            this.Admx = admx;
        }

        #region (properties)

        private AdmxFile Admx { get; set; }

        #endregion (properies)

        #region (methods)

        internal void UpdateDisplay()
        {
            this.nupMajorRevision.Value = (Decimal)this.Admx.Revision.Major;
            this.nupMinorRevision.Value = (Decimal)this.Admx.Revision.Minor;

            Namespace currentNamespace = this.Admx.TargetedNamespace;

            this.fltTxtBxNamespace.Text = currentNamespace.Target;
            this.fltTxtBxPrefix.Text = currentNamespace.Prefix;

            this.txtBxSupersedAdm.Text = this.Admx.SupersededAdm;

            this.nupMajorResources.Value = this.Admx.Resources.MinRequiredRevision.Major;
            this.nupMinorResources.Value = this.Admx.Resources.MinRequiredRevision.Minor;

            this.dgvUsingNamespaces.Rows.Clear();
            if (this.Admx.UsedNamespaces.Count != 0)
            {
                foreach (Namespace usedNamespace in this.Admx.UsedNamespaces)
                {
                    this.dgvUsingNamespaces.Rows.Add(new Object[] { usedNamespace.Prefix, usedNamespace.Target, usedNamespace });
                }
            }
            this.txtBxFallbackCulture.Text = this.Admx.Resources.FallbackCulture.Culture.DisplayName;
        }

        private void AddUsedNamespace()
        {
            //List<Namespace> availableNamespaces = new List<Namespace>();

            //foreach (AdmxProject project in this._main.OpenedProjects)
            //{
            //    if (!project.Equals(this.Project) && !this.Project.GetUsedNamespaces().Contains(project.GetNamespace()))
            //        availableNamespaces.Add(project.GetNamespace());
            //}

            //FrmAddNamespace frmAddNamespace = new FrmAddNamespace(availableNamespaces);
            //if (frmAddNamespace.ShowDialog() == DialogResult.OK && frmAddNamespace.Namespace != null)
            //{
            //    if (!Admx_Generator.Namespace.IsNamespaceInclude(frmAddNamespace.Namespace, this.Project))
            //    {
            //        this.Project.AddUsedNamespace(frmAddNamespace.Namespace);
            //        this.UpdateDisplay();
            //    }
            //    else
            //    { MessageBox.Show(this.GetLocalizedString("ThisNamespaceAlreadyExists")); }
            //}
        }

        private void EditUsedNamespace()
        {
            //Namespace selectedNamespace = (Namespace)this.dgvUsingNamespaces.SelectedRows[0].Cells["Namespace"].Value;

            //FrmEditPrefix editPrefix = new FrmEditPrefix(selectedNamespace.Prefix);

            //if (editPrefix.ShowDialog() == DialogResult.OK)
            //{
            //    Namespace newNamespace = this.Project.EditUsedNamespace(selectedNamespace, editPrefix.NewPrefix);
            //    List<Category> linkedCategories = this.Project.GetCategoriesLinkToPrefix(selectedNamespace.Prefix, this.Project.Admx);
            //    //foreach (Category category in linkedCategories)
            //    //{
            //    //    category.Namespace = newNamespace;
            //    //}

            //    List<Policy> linkedPolicies = this.Project.GetPoliciesLinkToPrefix(selectedNamespace.Prefix, this.Project.Admx);
            //    foreach (Policy policy in linkedPolicies)
            //    {
            //        // TODO Renommer le prefix dans le supportedOn des politiques
            //    }

            //    this.UpdateDisplay();
            //}
        }

        private void RemoveUsedNamespace()
        {
            Namespace selectedNamespace = (Namespace)this.dgvUsingNamespaces.SelectedRows[0].Cells["Namespace"].Value;
            // TODO Verifier que ce Namespace n'est pas utilisé par une Catégorie, et prévenir que la catégorie va être supprimé aussi
            //this.Project.RemoveUsedNamespace(selectedNamespace);
            this.UpdateDisplay();
        }

        private void BrowseForSupersededAdm()
        {
            OpenFileDialog admFileBrowser = new OpenFileDialog();

            admFileBrowser.Filter = "*.adm|*.adm";
            admFileBrowser.CheckFileExists = false;
            admFileBrowser.Multiselect = false;

            admFileBrowser.InitialDirectory = @"C:\Windows\PolicyDefinitions";
            if (admFileBrowser.ShowDialog() == DialogResult.OK)
            {
                System.IO.FileInfo admFile = new System.IO.FileInfo(admFileBrowser.FileName);
                this.Admx.SupersededAdm = admFile.Name;
                this.UpdateDisplay();
            }
        }

        /// <summary>
        /// Returns a localized string depending of the current culture.
        /// </summary>
        /// <param name="unlocalizedString">string to localized.</param>
        /// <returns>the localized string.</returns>
        protected string GetLocalizedString(string unlocalizedString)
        {
            string result = string.Empty;

            try
            {
                result = resMan.GetString(unlocalizedString);
                if (!string.IsNullOrEmpty(result))
                    return result;
            }
            catch (Exception) { }

            return "Missing_Localized_String_For(" + ((unlocalizedString != null) ? unlocalizedString : "null") + ")";
        }

        #endregion (methods)

        #region {UI Management}

        // Numeric UpDown Revision
        private void nupRevision_ValueChanged(object sender, EventArgs e)
        {
            this.Admx.Revision = new Revision((uint)this.nupMajorRevision.Value, (uint)this.nupMinorRevision.Value);
        }

        // Numeric UpDown Resources
        private void nupResources_ValueChanged(object sender, EventArgs e)
        {
            this.Admx.Revision = new Revision((uint)this.nupMajorResources.Value, (uint)this.nupMinorResources.Value);
        }

        private void fltTxtBxNamespace_TextChanged(object sender, EventArgs e)
        {
            try
            {
                this.Admx.TargetedNamespace = new Namespace(this.fltTxtBxNamespace.Text, this.fltTxtBxPrefix.Text);
            }
            catch (Exception ex) { MessageBox.Show(this.GetLocalizedString("AnErrorOccurredWhileEditingNamespace") + ex.Message); }
        }

        private void txtBxSupersedAdm_TextChanged(object sender, EventArgs e)
        {
            this.Admx.SupersededAdm = this.txtBxSupersedAdm.Text;
        }

        private void txtBxSupersedAdm_Leave(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtBxSupersedAdm.Text) && !this.txtBxSupersedAdm.Text.EndsWith(".adm", StringComparison.InvariantCultureIgnoreCase))
            {
                this.txtBxSupersedAdm.Text += ".adm";
                this.Admx.SupersededAdm = this.txtBxSupersedAdm.Text;
            }
        }

        private void dgvUsingNamespaces_SelectionChanged(object sender, EventArgs e)
        {
            //if (this.dgvUsingNamespaces.SelectedRows != null && this.dgvUsingNamespaces.SelectedRows.Count != 0)
            //{
            //    Namespace selectedNamespace = (Namespace)this.dgvUsingNamespaces.SelectedRows[0].Cells["Namespace"].Value;
            //    Namespace supportedOnNamespace = null;
            //    if (this.Project.GetSupportedOn() != null)
            //    {
            //        supportedOnNamespace = this.Project.GetSupportedOn().Namespace;
            //    }

            //    bool allowEditRemove = (supportedOnNamespace == null || !supportedOnNamespace.Equals(selectedNamespace));

            //    this.btnEditUsedNamespace.Enabled = allowEditRemove;
            //    this.btnRemoveUsedNamespace.Enabled = allowEditRemove;
            //}
        }

        private void dgvUsingNamespaces_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvUsingNamespaces.SelectedRows != null && this.dgvUsingNamespaces.SelectedRows.Count != 0)
            { this.btnEditUsedNamespace.PerformClick(); }
        }

        private void btnAddUsedNamespace_Click(object sender, EventArgs e)
        {
            try
            {
                this.AddUsedNamespace();
            }
            catch (Exception ex) { MessageBox.Show(this.GetLocalizedString("AnErrorOccurredWhileAddingUsedNamespace") + ex.Message); }
        }

        private void btnEditUsedNamespace_Click(object sender, EventArgs e)
        {
            try
            {
                this.EditUsedNamespace();
            }
            catch (Exception ex) { MessageBox.Show(this.GetLocalizedString("AnErrorOccurredWhileEditingUsedNamespace") + ex.Message); }
        }

        private void btnRemoveUsedNamespace_Click(object sender, EventArgs e)
        {
            try
            {
                RemoveUsedNamespace();
            }
            catch (Exception ex) { MessageBox.Show(this.GetLocalizedString("AnErrorOccurredWhileRemovingUsedNamespace") + ex.Message); }
        }

        private void btnBrowseAdm_Click(object sender, EventArgs e)
        {
            try
            {
                BrowseForSupersededAdm();
            }
            catch (Exception ex) { MessageBox.Show(this.GetLocalizedString("AnErrorOccurredWhileAddingSupersededADM") + ex.Message); }
        }

        #endregion {UI Management}
    }
}
